package com.eqxiu.ieditor.api.impl.mall;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import eqxiu.mall.product.dto.ProductCollectionDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.eqxiu.ieditor.api.mall.IMallProductServiceApi;
import com.eqxiu.ieditor.commons.dto.BaseResultData;
import com.eqxiu.ieditor.commons.dto.IdDTO;
import com.eqxiu.ieditor.commons.web.MsgCode;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.dto.mall.ProductCodeTypeInputDTO;
import com.eqxiu.ieditor.dto.mall.ProductPageInputDTO;

import eqxiu.mall.product.dto.PageDTO;
import eqxiu.mall.product.exception.ApiException;
import eqxiu.mall.product.service.api.ProductServiceApi;
import eqxiu.mall.product.service.api.SpecialServiceApi;

/**
 * @description 商城-商品service<br/>
 * 本类为重构后的结果，原代码写在ProductController中
 * @author 
 * @modified DuYoulong 重构 
 * @creatTime 2019年4月3日
 * @since 1.0.0
 */
public class MallProductServiceApiImpl implements IMallProductServiceApi, BaseResultData {

    private final Logger logger = LoggerFactory.getLogger(MallProductServiceApiImpl.class);

    private static final String COLLECT_FLAG = "collectVersion";
    @Autowired
    private ProductServiceApi productService;

    @Autowired
    private SpecialServiceApi specialService;
	
	/*@GetMapping("/api/product/by-code/{code}")
	public ResultData info(@PathVariable("code") String code) {

		Map<String, Object> prod = productService.getProductLiteByCodeAndAttrGroupId(code, 2);// productService.getListBySourceId("")

		if (prod == null) {
			return fail().setCode(MsgCode.DATA_NOT_EXIST).setMsg("product not exist");
		}

		return success().setMap(prod);
	}*/

    @Override
    public ResultData getByTypeAndCode(ProductCodeTypeInputDTO dto) {
        try {
            Map<String, Object> prod = productService.getProductLiteByCodeAndAttrGroupId(dto.getCode(), dto.getAttrGroupId());
            if (prod == null) {
                return fail().setCode(MsgCode.DATA_NOT_EXIST).setMsg("product not exist");
            }
            return success().setMap(prod);
        } catch (Exception e) {
            logger.error("根据商品场景code和商品品类类型attrGroupId获取商品异常={}", e);
            return fail();
        }

    }
	
	/*@PostMapping("/api/product/list")
	public ResultData list(@RequestParam Integer id, @RequestParam Integer pageNo, @RequestParam Integer pageSize,
			@RequestParam(required = false) Integer sort, @RequestParam(required = false) Integer priceRange) {
		Map<String, String> param = new HashMap<>();
		param.put("sort", extractSort(sort));
		param.put("priceRange", extractPriceRange(priceRange));

		PageDTO<Map<String, Object>> prods = productService.getProductByCategory(id, pageNo, pageSize, param);

		Map<String, Object> map = new HashMap<>();
		// map.put("count", prods.getCount());
		map.put("pageNo", pageNo);
		map.put("pageSize", pageSize);
		map.put("end", prods.isEnd());
		return success().setList(prods.getList()).setMap(map);
	}*/

    @Override
    public ResultData getPageListByCategoryId(ProductPageInputDTO dto) {
        // 1、封装入参
        Map<String, String> extendParam = new HashMap<>();
        extendParam.put("sort", extractSort(dto.getSort()));
        extendParam.put("priceRange", extractPriceRange(dto.getPriceRange()));

        try {
            // 2、查询操作
            PageDTO<Map<String, Object>> list = productService.getProductByCategory(dto.getCategoryId(),
                    dto.getPageNo(), dto.getPageSize(), extendParam);

            // 3、封装返回值
            Map<String, Object> map = new HashMap<>();
            map.put("pageNo", dto.getPageNo());
            map.put("pageSize", dto.getPageSize());
            map.put("end", list.isEnd());

            return success().setList(list.getList()).setMap(map);
        } catch (Exception e) {
            logger.error("根据分类id查询商品的详情列表异常={}", e);
            return fail();
        }
    }


	/*@GetMapping("/api/act/{actId}")
	public ResultData activityList(@PathVariable Integer actId) {
		List<Map<String, Object>> products;
		try {
			products = specialService.specialDetails(actId);
			return success().setList(products);
		} catch (ApiException e) {
			e.printStackTrace();
			return fail();
		}
	}*/

    @Override
    public ResultData getListBySpecialId(IdDTO dto) {
        try {
            List<Map<String, Object>> products = specialService.specialDetails(dto.getId());
            return success().setList(products);
        } catch (ApiException e) {
            logger.error("根据专题id查询专题下的商品信息异常={}", e);
            return fail();
        }
    }


    private String extractPriceRange(Integer priceRange) {
    	if (priceRange == null) {
			return "";
		}
        String priceRangeStr;
        switch (priceRange) {
            case 1:
                priceRangeStr = "";
                break;
            case 2:
                priceRangeStr = "0a100";
                break;
            case 3:
                priceRangeStr = "0a0";
                break;
            case 4:
                priceRangeStr = "1a10";
                break;
            case 5:
                priceRangeStr = "10a20";
                break;
            case 6:
                priceRangeStr = "20a30";
                break;
            case 7:
                priceRangeStr = "30a40";
                break;
            case 8:
                priceRangeStr = "40a50";
                break;
            case 9:
                priceRangeStr = "50a60";
                break;

            default:
                priceRangeStr = "";
                break;
        }
        return priceRangeStr;
    }

    private String extractSort(Integer sort) {
    	if (sort == null) {
			return "sort|desc";
		}
        String sortStr;
        switch (sort) {
            case 1:
                sortStr = "sort|desc";
                break;
            case 2:
                sortStr = "create_time|desc";
                break;
            case 3:
                sortStr = "product_usage|desc";
                break;

            default:
                sortStr = "sort|desc";
                break;
        }
        return sortStr;
    }

    @Override
    public ResultData getByProductId(Integer productId) {
        try {
            Map<String, Object> productLiteForSearch = productService.getProductLiteForSearch(productId);
            //判断是否有商品集版本标识
            if (productLiteForSearch != null && productLiteForSearch.containsKey(COLLECT_FLAG)) {
                ProductCollectionDTO productCollectByProductId = productService.getProductCollectByProductId(productId);
                if (productCollectByProductId != null) {
                    productLiteForSearch.put("collectFreeId", productCollectByProductId.getFreeProductId());
                    productLiteForSearch.put("collectStandardId", productCollectByProductId.getStandardProductId());
                    productLiteForSearch.put("collectHighId", productCollectByProductId.getHighProductId());
                }
            }
            return success().setMap(productLiteForSearch);
        } catch (Exception e) {
            logger.error("根据商品id查询商品信息异常={}", e);
            return fail();
        }
    }
}
